package com.arvato.common.util;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;

public class JdomUtil {
	
	private static Logger logger = LoggerFactory.getLogger(JdomUtil.class);
	
	public static Map<String, String> xmlElements(String xmlStr) {
		Map<String, String> resultMap = new HashMap<String, String>();
		// 创建一个新的字符串 12
		StringReader read = new StringReader(xmlStr);
		// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
		InputSource source = new InputSource(read);
		// 创建一个新的SAXBuilder
		SAXBuilder sb = new SAXBuilder();
		try {
			// 通过输入源构造一个Document
			Document doc = sb.build(source);
			// 取的根元素
			Element root = doc.getRootElement();
			logger.info(root.getName());// 输出根元素的名称（测试）
			// 得到根元素所有子元素的集合
			@SuppressWarnings("unchecked")
			List<Element> childList = root.getChildren();
			for (int i = 0; i < childList.size(); i++) {
				Element child = childList.get(i);// 循环依次得到子元素
				resultMap.put(child.getName(), child.getText());
				logger.info(child.getName() + " : " + child.getText());
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	public static void main(String[] args) {
		String xml = "<xml><ToUserName><![CDATA[oia2TjjewbmiOUlr6X-1crbLOvLw]]></ToUserName><FromUserName><![CDATA[gh_7f083739789a]]></FromUserName><CreateTime>1407743423</CreateTime><MsgType><![CDATA[video]]></MsgType><Video><MediaId><![CDATA[eYJ1MbwPRJtOvIEabaxHs7TX2D-HV71s79GUxqdUkjm6Gs2Ed1KF3ulAOA9H1xG0]]></MediaId><Title><![CDATA[testCallBackReplyVideo]]></Title><Description><![CDATA[testCallBackReplyVideo]]></Description></Video></xml>  \r\n";
		JdomUtil.xmlElements(xml);
	}
}
